package com.zhuhao.utils.httpclient;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.zhuhao.basic.collection.domain.User;
import org.junit.Test;
import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * spring封装的http工具
 *
 * @Author haozhu7
 * @Date 2024/2/27 15:15
 **/
public class SpringHttpClientUtils {

    private static RestTemplate restTemplate;

    static {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setReadTimeout(10000);
        requestFactory.setConnectTimeout(5000);
        // 添加转换器
        List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
        messageConverters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
        messageConverters.add(new FormHttpMessageConverter());
        messageConverters.add(new MappingJackson2HttpMessageConverter());
        restTemplate = new RestTemplate(messageConverters);
        restTemplate.setRequestFactory(requestFactory);
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
    }

    /**
     * 封装get请求
     *
     * @param url
     * @param paramMap
     * @return
     */
    public static Object doSignedGet(String url, Map<String, String> headerMap, Map<String, String> paramMap) {
        String targetUrl = paramsProcess(url, paramMap);
        return requestForObject(targetUrl, HttpMethod.GET, Object.class, headerMap, null);
    }

    /**
     * 封装post请求
     *
     * @param url
     * @param paramObj
     * @return
     */
    public static Object doSignedPost(String url, Map<String, String> headerMap, Object paramObj) {
        return requestForObject(url, HttpMethod.POST, Object.class, headerMap, paramObj);
    }

    /**
     * 参数处理
     *
     * @param url
     * @param paramMap
     * @return
     */
    private static String paramsProcess(String url, Map<String, String> paramMap) {
        if (CollectionUtil.isEmpty(paramMap)) {
            return url;
        }
        StringBuilder params = new StringBuilder();
        for (String key : paramMap.keySet()) {
            params.append(key).append("=").append(paramMap.get(key)).append("&");
        }

        return url + (url.contains("?") ? "&" : "?") + params;
    }

    public static <T> T requestForObject(String url, HttpMethod method, Class<T> responseType, Map<String, String> headerMap, Object params) {
        HttpHeaders headers = new HttpHeaders();
        if (CollectionUtil.isNotEmpty(headerMap)) {
            headerMap.forEach(headers::add);
        }
        headers.setContentType(MediaType.parseMediaType("application/json; charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());

        String paramsJson = params.toString();
        if (!JSONUtil.isJson(params.toString())) {
            paramsJson = JSONUtil.parse(params).toJSONString(2);
        }
        HttpEntity<String> requestEntity = new HttpEntity<>(paramsJson, headers);
        ResponseEntity<T> responseEntity = restTemplate.exchange(url, method, requestEntity, responseType);
        return responseEntity.getBody();
    }


    @Test
    public void test01() {
        String url = "http://192.168.6.20:8888/param/list/请假原因";
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("token", "eyJhbGciOiJIUzI1NiIsInppcCI6IkdaSVAifQ.H4sIAAAAAAAAAIXPMY7CMBAF0LtMTWHH48GmQ6KhoVhRuknImI0INkqIdldR7kDPNRA3gnNskgW0HdI0_8-bYlqomwxm0DpI830R1j8HdjATEwdFPR-aV1rEJiv5I5YDkH1Vxm0RVul-yA6-mmMaHfR9xb7i-nMddxzGlVVWTA2S18oj5psMrUIv2LBnspr-rmI8LvPRS0Qi0khWkhK6HzOSJhRvSc3Vi5CR0hqDAjURJv_I4035iOH5xO10uV_PDjqYAH8fekFaisRSorpfTzyfzysBAAA.VhQVVoVXB-reg1JX0UnCW4-k9VdgIECdi6ThrlO1es0");

        Object o = SpringHttpClientUtils.doSignedGet("https://www.baidu.com/", null, null);
        System.out.println(o);
    }

    @Test
    public void testRestTemplate() throws URISyntaxException {
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://127.0.0.1:8787/put";
//        RequestEntity<String> requestEntity = new RequestEntity<String>();
        //获取指定技能队列排队总人数
        RequestEntity<Void> requestEntity = RequestEntity.put(new URI(url))
                .header("Guid", "sfosdfoijsifjijeifjewijf21321.gaway")
                .build();

        System.out.println(requestEntity.toString());
        ResponseEntity<String> exchange = restTemplate.exchange(requestEntity, String.class);
        System.out.println(exchange.getBody());


        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.put("Guid", Arrays.asList("sfosdfoijsifjijeifjewijf21321.gaway", "this is second"));
        User user = new User("halk", 11, 22D);

        HttpEntity<String> httpEntity = new HttpEntity<String>(JSON.toJSONString(user), httpHeaders);
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.PUT, httpEntity, String.class);
        System.out.println(responseEntity.getBody().toString());
    }
}
